use std::error::Error;

use cs2s::{
    cache::{CacheTableClientHandle, CacheTableConfig},
    utils::{mangle::PathStrExt, map::Config},
};
use tabled::Tabled;

use crate::{args::TableListCommand, table::visualize::visualize, ARGS};

#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "linux")]
pub use linux::list;

#[cfg(not(target_os = "linux"))]
mod other;
#[cfg(not(target_os = "linux"))]
pub use other::list;

/// List all cache tables.
fn list_tables<I, S>(command: &TableListCommand, tables: I) -> Result<(), Box<dyn Error>>
where
    I: IntoIterator<Item = S>,
    S: AsRef<str>,
{
    #[derive(Tabled)]
    #[tabled(rename_all = "Pascal")]
    struct TableListing {
        path: String,
        capacity: usize,
        usage: usize,
    }

    let tables = tables.into_iter().filter_map(|table| {
        let table =
            table
                .as_ref()
                .strip_prefix(&format!("{}{}-", CacheTableConfig::PREFIX, ARGS.name))?;
        let handle = CacheTableClientHandle::new(&format!("{}-{}", ARGS.name, table)).ok()?;
        let capacity = handle.capacity();
        let usage = handle.usage();

        Some(TableListing {
            path: table.demangle(),
            capacity,
            usage,
        })
    });

    visualize(command.shared_args.style, tables);

    Ok(())
}
